<?php
namespace App\Http\Controllers\Api;

use App\Businesses\BusinessState;
use App\Services\Order\Models\RedeemCode;
use App\Http\Requests\ApiV2\RedeemCodeRequest;
use App\Services\Member\Services\UserService;
use App\Services\Member\Interfaces\UserServiceInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use  Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class RedeemCodeController extends BaseController
{


    protected $businessState;
    /**
     * @var UserService
     */
    protected $userService;

    public function __construct(BusinessState $businessState, UserServiceInterface $userService)
    {

        $this->businessState = $businessState;
        $this->userService = $userService;

    }

    public function index(Request $request)
    {
        $code = $request->input('code');
        // 排序
        $items = RedeemCode::query()
            ->when($code, function ($query) use ($code) {
                $query->where('code', 'like', '%' . $code . '%');
            })
            ->orderBy('created_at')
            ->paginate($request->input('size', 10));

        return $this->successData($items);
    }



    /**领券
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function claim(Request $request, int $id)
    {
        $user = Auth::user();
        $code = RedeemCode::find($id);
        if (!$code && !$this->businessState->redeemCodeCanUse($code->toArray())) {

            return $this->success(__('还没有到兑换条件,请核对'));
        }
        if (!$user->redeemCodes()->where('redeem_code_id', $id)->exists()) {
            $user->redeemCodes()->attach($id, [
                'claim_at' => now(),
            ]);
            $code->increment('claim_count');

            return $this->success(__('兑换码已经成功领取'));
        } else {

            return $this->error(__('优惠券您领取过，无需重复再领取'));

        }


    }

    //置换

    /**
     * @param Request $request
     * @param string $type
     * @param int $id
     * @return mixed
     */
    public function redeem(Request $request, string $type, int $id)
    {


        $user = Auth::user();
        $code = $request->input('code');
        $redeemCode = RedeemCode::query()->where('code', $code)->first();
        $UserModel = 'App\Services\Member\Models\User' . $type;
        $UserModel = new  $UserModel();
        return DB::transaction(function () use ($type, $id, $user, $code, $redeemCode, $UserModel) {
            if ($user->redeemCodes()->where('redeem_code_id', $redeemCode->id)->exists()) {

                $userService = app()->make(UserServiceInterface::class);
                $methodName = 'has' . ucfirst($type);
                    if ($userService->$methodName($user->id,$id)) {
                        return $this->error(__('课程无需重复兑换'));
                    }


                //更新兑换码状态
                $user->redeemCodes()->where('redeem_code_id', $redeemCode->id)->update(['is_used' => 1]);
                $redeemCode->increment('used_times');

                //开通课程
                $UserModel::create([
                    'user_id' => $user->id,
                    $type . '_id' => $id,
                    'created_at' => now(),
                    'remark' => '兑换券导入'

                ]);

                return $this->success(__('兑换成功'));
            }


        });


    }

    public function store(RedeemCodeRequest $request)
    {
        $data = $request->filldata();
        RedeemCode::create($data);
        return $this->success(__('兑换码码插入成功'));
    }

    public function edit($id)
    {
        $info = RedeemCode::query()
            ->with(['products'])
            ->where('id', $id)
            ->first();
        return $this->successData($info);
    }

    public function update(RedeemCodeRequest $request, $id)
    {
        $item = RedeemCode::findOrFail($id);
        $item->fill($request->filldata())->save();
        return $this->success(__('兑换码更新成功'));
    }



    public function delete(Request $request, $id)
    {

        $promoCode = RedeemCode::find($id);
        $promoCode->delete();
        return $this->success(__('删除兑换码成功'));
    }

    public function productStore(Request $request, $id)
    {


        $code = RedeemCode::query()->where('id', $id)->firstOrFail();
        $products = $request->input('products', []);
        $code->products()->createMany($products);
        return $this->success(__('添加商品成功'));


    }

    public function productDelete(Request $request, $id)
    {


        $code = RedeemCode::query()->where('id', $id)->firstOrFail();
        $ids = $request->input('ids', []);
        $code->products()->whereIn('id', $ids)->delete();
        return $this->success(__('取消商品成功'));


    }

    public function detail(Request $request, $codeId)
    {

        $code = RedeemCode::query()
            ->where('id', $codeId)
            ->with(['products', 'claimers'])
            ->first()->toArray();
        $isClaimed = 0;
        if ($this->check()) {

            $userId = $this->id();
            $isClaimed = $this->userService->isClaimedCode($userId, $codeId);
        }

        return $this->successData(compact('code', 'isClaimed'));


    }


    public function checkCode($code)
    {

        $coupon = RedeemCode::query()->where('code', $code)->first()->toArray();
        $canUse = 0;
        if ($this->check()) {
            $canUse = (int)$this->businessState->redeemCodeCanUse($this->id(), $coupon);
        }
        return $this->data(['coupon' => $coupon, 'canUse' => $canUse]);
    }

}
